package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.client.DictFeignClient;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.enums.DictEnum;
import com.atguigu.yygh.hosp.mapper.HospitalSetMapper;
import com.atguigu.yygh.hosp.repository.HospitalRepository;
import com.atguigu.yygh.hosp.service.HospitalService;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.model.hosp.HospitalSet;
import com.atguigu.yygh.vo.hosp.HospitalQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class HospitalServiceImpl implements HospitalService {

//    Mongodb
    @Autowired
    private HospitalRepository hospitalRepository;

//    Mysql
    @Autowired
    private HospitalSetMapper hospitalSetMapper;

//    注入OpenFeign
    @Autowired
    private DictFeignClient dictFeignClient;

    @Override
    public void saveHospital(Map<String, Object> resultMap) {
//        把Map集合转化为JSON对象
        String str = JSONObject.toJSONString(resultMap);
        Hospital hospital = JSONObject.parseObject(str, Hospital.class);
        String hoscode = hospital.getHoscode();

        Hospital resultHosp= hospitalRepository.findByHoscode(hoscode);
        if (resultHosp == null){ //平台上没有医院信息则进行添加操作

            hospital.setCreateTime(new Date());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
//            0: 未上线 1 : 已上线
            hospital.setStatus(0);
            hospitalRepository.save(hospital);
        }else{ //平台上又医院的信息则进行修改操作
            hospital.setIsDeleted(resultHosp.getIsDeleted());
            hospital.setCreateTime(resultHosp.getCreateTime());
            hospital.setStatus(resultHosp.getStatus());
            hospital.setUpdateTime(new Date());

            hospital.setId(resultHosp.getId());
            hospitalRepository.save(hospital);
        }
    }


    @Override
    public String getSignKeyWithHosecode(String requestHouseCode) {
//        Mybatis_plus -->医院是否存在在数据库内
        QueryWrapper<HospitalSet> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("hoscode", requestHouseCode);
        HospitalSet hospitalSet = hospitalSetMapper.selectOne(queryWrapper);

//        判断查询的条件是否为空
        if (StringUtils.isEmpty(hospitalSet)){
            throw  new YyghException(20001,"该医院信息不存在");
        }
        return hospitalSet.getSignKey();
    }

//    通过Hoscode获取到Hospital对象
    @Override
    public Hospital getHospitalByHoscode(String hoscode) {
        return hospitalRepository.findByHoscode(hoscode);
    }

//    分页查询医院信息
    @Override
    public Page<Hospital> getHospitalPage(Integer pageNum, Integer pageSize, HospitalQueryVo hospitalQueryVo) {
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime").ascending();
        //0为第一页
        Pageable pageable = PageRequest.of(pageNum-1, pageSize, sort);

        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo, hospital);

        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withMatcher("hosname",ExampleMatcher.GenericPropertyMatchers.contains()) //名字字段进行模糊匹配
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写

        //创建实例
        Example<Hospital> example = Example.of(hospital, matcher);
        Page<Hospital> pages = hospitalRepository.findAll(example, pageable);
        //封装医院等级数据
        pages.getContent().forEach(this::packHospital);
        return pages;
    }

//    修改医院的Status字段
    /*
    * 思路 : 先从MongoDb中获取到Hospital对象 然后再进行修改
    * */
    @Override
    public void updateStatus(String id, Integer status) {
//        进行状态码的验证 状态码只可能是0或者是1
        if (status ==0 || status ==1){
//        在Mongdb数据库中通过Id查询到对象
            Hospital resultMonObj = hospitalRepository.findById(id).get();
            resultMonObj.setStatus(status);
            resultMonObj.setUpdateTime(new Date());
            hospitalRepository.save(resultMonObj);
        }
    }

//    通过Id获取Hospital对象
    @Override
    public Hospital detail(String id) {
        /*
        * 注意:
        *       从MongoDb中获取的是医院的编号信息而不是文字信息
        * */
        Hospital hospital = hospitalRepository.findById(id).get();
        this.packHospital(hospital);
        return hospital;
    }


//    根据医院名称对医院进行模糊查询
    @Override
    public List<Hospital> findByName(String hosName) {
        return hospitalRepository.findHospitalByHosnameLike(hosName);
    }

//    根据医院的编号进行查询
    @Override
    public Hospital getHospitalDetail(String hoscode) {
        Hospital hospital = hospitalRepository.findByHoscode(hoscode);
        this.packHospital(hospital);
        return hospital;
    }

//    自定义封装方法,将Mongdb中的code属性值 转化为字符串类型
    private void packHospital(Hospital hospital) {
        String hostypeString = dictFeignClient.getName(DictEnum.HOSTYPE.getDictCode(),hospital.getHostype());
        String provinceString = dictFeignClient.getName(hospital.getProvinceCode());
        String cityString = dictFeignClient.getName(hospital.getCityCode());
        String districtString = dictFeignClient.getName(hospital.getDistrictCode());

        hospital.getParam().put("hostypeString", hostypeString);
        hospital.getParam().put("fullAddress", provinceString + cityString + districtString + hospital.getAddress());
    }

}
